package cn.ctyun.videoplayer.controller;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import cn.ctyun.videoplayer.R;
import cn.ctyun.videoplayer.bean.MarqueeTextDetail;
import cn.ctyun.videoplayer.bean.WaterMarkTextDetail;
import cn.ctyun.videoplayer.dlnaupnp.entity.ClingDevice;
import cn.ctyun.videoplayer.player.IjkVideoView;
import cn.ctyun.videoplayer.receive.BatteryReceiver;
import cn.ctyun.videoplayer.util.SDKLog;
import cn.ctyun.videoplayer.widget.MarqueeView;
import cn.ctyun.videoplayer.util.PlayerConstants;
import cn.ctyun.videoplayer.util.PlayerUtils;
import cn.ctyun.videoplayer.util.Utils;
import cn.ctyun.videoplayer.widget.MarqueeTextView;

import static android.support.annotation.Dimension.SP;

/**
 * 直播/点播控制器
 * Created by Devlin_n on 2017/4/7.
 */

public class StandardVideoController extends GestureVideoController implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {
    private static final String TAG = "CHL_" + StandardVideoController.class.getSimpleName();

    protected TextView mTotalTime, mCurrTime;
    protected ImageView mFullScreenButton;
    protected LinearLayout mBottomContainer, mTopContainer;
    protected SeekBar mVideoProgress;
    protected ImageView mBackButton;
    protected ImageView mLockButton;
    protected MarqueeTextView mTitle;
    private boolean mIsLive;
    private boolean mIsDragging;
    protected TextView mTvSpeed;

    private ProgressBar mBottomProgress;
    private ImageView mPlayButton;
    private ImageView mStartPlayButton;
    private ProgressBar mLoadingProgress;
    private ImageView mThumb;
    private LinearLayout mCompleteContainer;
    private TextView mSysTime;//系统当前时间
    private ImageView mBatteryLevel;//电量
    private Animation mShowAnim = AnimationUtils.loadAnimation(getContext(), R.anim.dkplayer_anim_alpha_in);
    private Animation mHideAnim = AnimationUtils.loadAnimation(getContext(), R.anim.dkplayer_anim_alpha_out);
    private BatteryReceiver mBatteryReceiver;
    protected ImageView mRefreshButton;
    protected ImageView mDLNAButton;
    private DLNAControllerInterface dlnaListener;

    private RelativeLayout mRlPauseAd;

    private ImageView mIvPauseAd;
    private LinearLayout mLlCloseAd;
    private ImageView mIvcloseAd;
    private TextView mTvCloseAd;
    private TextView mTvAdDesc;

    private boolean isPauseAdAvailable = false;
    private RelativeLayout mRlDLNAConnected_port;
    private TextView mTvDeviceName_port;
    private TextView mTvConnectedState_port;
    private LinearLayout mLLDLNAChangeDeivce_port;
    private LinearLayout mLLDLNAExit_port;

    private RelativeLayout mRlDLNAConnected_land;
    private TextView mTvDeviceName_land;
    private TextView mTvConnectedState_land;
    private LinearLayout mLLDLNAChangeDeivce_land;
    private LinearLayout mLLDLNAExit_land;
    private boolean mDLNAConnected;
    private boolean mFullScreen;

    private RelativeLayout mRlWatermark;
    private TextView mTvWatermark;
    private MarqueeView mMarqueeView;

    public StandardVideoController(@NonNull Context context) {
        this(context, null);
    }

    public StandardVideoController(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public StandardVideoController(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dkplayer_layout_standard_controller;
    }

    @Override
    protected void initView() {
        super.initView();
        mFullScreenButton = mControllerView.findViewById(R.id.fullscreen);
        mFullScreenButton.setOnClickListener(this);
        mBottomContainer = mControllerView.findViewById(R.id.bottom_container);
        mTopContainer = mControllerView.findViewById(R.id.top_container);
        mVideoProgress = mControllerView.findViewById(R.id.seekBar);
        mVideoProgress.setOnSeekBarChangeListener(this);
        mTotalTime = mControllerView.findViewById(R.id.total_time);
        mCurrTime = mControllerView.findViewById(R.id.curr_time);
        mBackButton = mControllerView.findViewById(R.id.back);
        mBackButton.setOnClickListener(this);
        mLockButton = mControllerView.findViewById(R.id.lock);
        mLockButton.setOnClickListener(this);
        mThumb = mControllerView.findViewById(R.id.thumb);
        mThumb.setOnClickListener(this);
        mPlayButton = mControllerView.findViewById(R.id.iv_play);
        mPlayButton.setOnClickListener(this);
        mStartPlayButton = mControllerView.findViewById(R.id.start_play);
        mStartPlayButton.setOnClickListener(this);
        mLoadingProgress = mControllerView.findViewById(R.id.loading);
        mBottomProgress = mControllerView.findViewById(R.id.bottom_progress);
        ImageView rePlayButton = mControllerView.findViewById(R.id.iv_replay);
        rePlayButton.setOnClickListener(this);
        mCompleteContainer = mControllerView.findViewById(R.id.complete_container);
        mCompleteContainer.setOnClickListener(this);
        mTitle = mControllerView.findViewById(R.id.title);
        mSysTime = mControllerView.findViewById(R.id.sys_time);
        mBatteryLevel = mControllerView.findViewById(R.id.iv_battery);
        mBatteryReceiver = new BatteryReceiver(mBatteryLevel);
        mRefreshButton = mControllerView.findViewById(R.id.iv_refresh);
        mRefreshButton.setOnClickListener(this);
        mTvSpeed = mControllerView.findViewById(R.id.tv_speed);
        mTvSpeed.setOnClickListener(this);

        mDLNAButton = mControllerView.findViewById(R.id.iv_dlna_touping);
        mDLNAButton.setOnClickListener(this);

        mRlPauseAd = mControllerView.findViewById(R.id.rl_pause_ad);
        mRlPauseAd.setOnClickListener(this);
        mIvPauseAd = mControllerView.findViewById(R.id.iv_pause_ad);
        mIvcloseAd = mControllerView.findViewById(R.id.iv_close_ad);
        mIvcloseAd.setOnClickListener(this);
        mTvCloseAd = mControllerView.findViewById(R.id.tv_close_ad);
        mTvCloseAd.setOnClickListener(this);
        mTvAdDesc = mControllerView.findViewById(R.id.tv_ad_desc);
        mLlCloseAd = mControllerView.findViewById(R.id.ll_close_ad);

        mRlDLNAConnected_port = mControllerView.findViewById(R.id.rl_dlna_connected_port);
        mTvDeviceName_port = mControllerView.findViewById(R.id.tv_dlna_connected_device_name_port);
        mTvConnectedState_port = mControllerView.findViewById(R.id.tv_dlna_connected_state_port);
        mLLDLNAChangeDeivce_port = mControllerView.findViewById(R.id.ll_dlna_connected_change_device_port);
        mLLDLNAExit_port = mControllerView.findViewById(R.id.ll_dlna_connected_exit_port);

        mLLDLNAChangeDeivce_port.setOnClickListener(this);
        mLLDLNAExit_port.setOnClickListener(this);

        mRlDLNAConnected_land = mControllerView.findViewById(R.id.rl_dlna_connected_land);
        mTvDeviceName_land = mControllerView.findViewById(R.id.tv_dlna_connected_device_name_land);
        mTvConnectedState_land = mControllerView.findViewById(R.id.tv_dlna_connected_state_land);
        mLLDLNAChangeDeivce_land = mControllerView.findViewById(R.id.ll_dlna_connected_change_device_land);
        mLLDLNAExit_land = mControllerView.findViewById(R.id.ll_dlna_connected_exit_land);

        mLLDLNAChangeDeivce_land.setOnClickListener(this);
        mLLDLNAExit_land.setOnClickListener(this);

        mRlWatermark = mControllerView.findViewById(R.id.rl_watermark);
        mTvWatermark = mControllerView.findViewById(R.id.tv_watermark);

        mMarqueeView = mControllerView.findViewById(R.id.marqueeview);
        mMarqueeView.setOnClickListener(this);
    }

    public void showMarquee(MarqueeTextDetail marqueeText) {
        if (marqueeText != null){
            mMarqueeView.setAlpha(0.0f);
            mMarqueeView.setVisibility(VISIBLE);
            mMarqueeView.setContent(marqueeText.getText());
            mMarqueeView.animate().alpha(1f).setDuration(2000)
                    .setListener(null);
        } else {
            mMarqueeView.setVisibility(GONE);
            mMarqueeView.setContent("");
        }
    }

    @Override
    public void setMediaPlayer(BaseMediaPlayerControlInterface mediaPlayer) {
        super.setMediaPlayer(mediaPlayer);
        if (mediaPlayer != null) {
            if (mediaPlayer.isFullScreen()) {
                mFullScreenButton.setVisibility(GONE);
            } else {
                mFullScreenButton.setVisibility(VISIBLE);
            }
            if (!TextUtils.isEmpty(mediaPlayer.getPauseAdUrl())) {
                isPauseAdAvailable = true;
                Glide.with(mAttachActivity).load(mediaPlayer.getPauseAdUrl()).addListener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        mTvAdDesc.setVisibility(VISIBLE);
                        mLlCloseAd.setVisibility(VISIBLE);
                        return false;
                    }
                }).into(mIvPauseAd);
            }
            if (!TextUtils.isEmpty(mThumbUrl)) {
                Glide.with(mAttachActivity).load(mThumbUrl).into(mThumb);
            }

            WaterMarkTextDetail watermark = mMediaPlayer.getWatermark();
            if (watermark != null) {
                mTvWatermark.setTextColor(watermark.getColor());
                mTvWatermark.setTextSize(watermark.getFontSize());
                mTvWatermark.setText(watermark.getText());
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mTvWatermark.getLayoutParams();
                if (PlayerConstants.WatermarkTextPosition.TOP_LEFT.equals(watermark.getPosition())) {
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                } else if (PlayerConstants.WatermarkTextPosition.TOP_RIGHT.equals(watermark.getPosition())) {
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                } else if (PlayerConstants.WatermarkTextPosition.BOTTOM_LEFT.equals(watermark.getPosition())) {
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                } else if (PlayerConstants.WatermarkTextPosition.BOTTOM_RIGHT.equals(watermark.getPosition())) {
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                } else {
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                }
            }
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        getContext().unregisterReceiver(mBatteryReceiver);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        getContext().registerReceiver(mBatteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.fullscreen) {
            doStartStopFullScreen();
        } else if (i == R.id.back) {
            mAttachActivity.onBackPressed();
        } else if (i == R.id.lock) {
            doLockUnlock();
        } else if (i == R.id.iv_play || i == R.id.start_play) {
            doPauseResume();
        } else if (i == R.id.iv_replay) {
            mMediaPlayer.retry();
        } else if (i == R.id.iv_refresh) {
            mMediaPlayer.refresh();
        } else if (i == R.id.iv_dlna_touping) {
            Log.d(TAG, "\n\n\n**************  onClick()  iv_dlna_touping   dlnaListener=" + dlnaListener);
            dlnaListener.onDLNAConnectClick();
        } else if (i == R.id.ll_dlna_connected_change_device_land || i == R.id.ll_dlna_connected_change_device_port) {
            Log.d(TAG, "\n\n\n**************  onClick()  ll_dlna_connected_change_device");
            dlnaListener.onDLNAChangeDeviceClick();
        } else if (i == R.id.ll_dlna_connected_exit_land || i == R.id.ll_dlna_connected_exit_port) {
            Log.d(TAG, "\n\n\n**************  onClick()  ll_dlna_connected_exit");
            dlnaListener.onDLNAExitClick();
        } else if (i == R.id.iv_close_ad || i == R.id.tv_close_ad) {
            mRlPauseAd.setVisibility(GONE);
        } else if (i == R.id.tv_speed) {
            if (mTvSpeed.getText().equals("1.0X")) {
                mMediaPlayer.setSpeed(1.25f);
                mTvSpeed.setText("1.25X");
            } else if (mTvSpeed.getText().equals("1.25X")) {
                mMediaPlayer.setSpeed(1.5f);
                mTvSpeed.setText("1.5X");
            } else if (mTvSpeed.getText().equals("1.5X")) {
                mMediaPlayer.setSpeed(1.0f);
                mTvSpeed.setText("1.0X");
            }
        } else if (i == R.id.rl_pause_ad) {
            if (mMediaPlayer.getOnPauseAdClickListener() != null) {
                mMediaPlayer.getOnPauseAdClickListener().click();
            }
        } else if (i == R.id.marqueeview) {
            if (mMediaPlayer.getMarqueeViewListener() != null) {
                mMediaPlayer.getMarqueeViewListener().onClick();
            }
        }
    }

    public void showDLNAIcon() {
        mDLNAButton.setVisibility(VISIBLE);
    }

    public void setControllerListener(DLNAControllerInterface listener) {
        this.dlnaListener = listener;
    }

    public void setConnectedDevice(ClingDevice connectedDevice) {
        mTvDeviceName_port.setText(connectedDevice.getDevice().getDetails().getFriendlyName());
        mTvDeviceName_land.setText(connectedDevice.getDevice().getDetails().getFriendlyName());
    }


    public void showTitle() {
        mTitle.setVisibility(VISIBLE);
    }

    @Override
    public void setPlayerState(int playerState) {
        super.setPlayerState(playerState);
        switch (playerState) {
            case IjkVideoView.PLAYER_NORMAL:
                if (mIsLocked) return;
                setLayoutParams(new LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT));
                mIsGestureEnabled = false;
                mFullScreenButton.setVisibility(VISIBLE);
                mTvSpeed.setVisibility(GONE);
                mBackButton.setVisibility(VISIBLE);
                mLockButton.setVisibility(GONE);
                mTitle.setVisibility(INVISIBLE);
                mSysTime.setVisibility(GONE);
                mBatteryLevel.setVisibility(GONE);
                if (isPauseAdAvailable) {
                    resizePauseAd(false);
                }
                mFullScreen = false;
                mRlDLNAConnected_port.setVisibility(mDLNAConnected ? VISIBLE : GONE);
                mRlDLNAConnected_land.setVisibility(GONE);
                break;
            case IjkVideoView.PLAYER_FULL_SCREEN:
                if (mIsLocked) return;
                mIsGestureEnabled = true;
                mFullScreenButton.setVisibility(GONE);
                if (mIsLive) {
                    mTvSpeed.setVisibility(GONE);
                } else {
                    mTvSpeed.setVisibility(VISIBLE);
                }

                mTitle.setVisibility(VISIBLE);
                mSysTime.setVisibility(VISIBLE);
                mBatteryLevel.setVisibility(VISIBLE);
                if (mShowing) {
                    mLockButton.setVisibility(VISIBLE);
                    mBackButton.setVisibility(VISIBLE);
                    mTopContainer.setVisibility(VISIBLE);
                } else {
                    mBackButton.setVisibility(GONE);
                    mLockButton.setVisibility(GONE);
                }
                if (isPauseAdAvailable) {
                    resizePauseAd(true);
                }

                mFullScreen = true;
                mRlDLNAConnected_port.setVisibility(GONE);
                mRlDLNAConnected_land.setVisibility(mDLNAConnected ? VISIBLE : GONE);
                break;
        }
    }

    @Override
    public void setPlayState(int playState) {
        super.setPlayState(playState);
        switch (playState) {
            case IjkVideoView.STATE_IDLE:
                SDKLog.info(TAG, "STATE_IDLE");
                hide();
                mIsLocked = false;
                mLockButton.setSelected(false);
                mMediaPlayer.setLock(false);
                mBottomProgress.setProgress(0);
                mBottomProgress.setSecondaryProgress(0);
                mVideoProgress.setProgress(0);
                mVideoProgress.setSecondaryProgress(0);
                mCompleteContainer.setVisibility(GONE);
                mBottomProgress.setVisibility(GONE);
                mLoadingProgress.setVisibility(GONE);
                mStartPlayButton.setVisibility(VISIBLE);
                mThumb.setVisibility(VISIBLE);
                handleWatermarkVisible(GONE);
                break;
            case IjkVideoView.STATE_PLAYING:
                SDKLog.info(TAG, "STATE_PLAYING");
                post(mShowProgress);
                mPlayButton.setSelected(true);
                mLoadingProgress.setVisibility(GONE);
                mCompleteContainer.setVisibility(GONE);
                mThumb.setVisibility(GONE);
                mStartPlayButton.setVisibility(GONE);
                handleWatermarkVisible(VISIBLE);
                break;
            case IjkVideoView.STATE_PAUSED:
                SDKLog.info(TAG, "STATE_PAUSED");
                mPlayButton.setSelected(false);
                mStartPlayButton.setVisibility(GONE);
                mThumb.setVisibility(GONE);
                handleWatermarkVisible(VISIBLE);
                break;
            case IjkVideoView.STATE_PREPARING:
                SDKLog.info(TAG, "STATE_PREPARING");
                mCompleteContainer.setVisibility(GONE);
                mStartPlayButton.setVisibility(GONE);
                mLoadingProgress.setVisibility(VISIBLE);
                handleWatermarkVisible(GONE);
                break;
            case IjkVideoView.STATE_PREPARED:
                SDKLog.info(TAG, "STATE_PREPARED");
                if (!mIsLive) mBottomProgress.setVisibility(VISIBLE);
                mStartPlayButton.setVisibility(GONE);
                handleWatermarkVisible(GONE);
                break;
            case IjkVideoView.STATE_ERROR:
                SDKLog.info(TAG, "STATE_ERROR");
                mStartPlayButton.setVisibility(GONE);
                mLoadingProgress.setVisibility(GONE);
                mThumb.setVisibility(GONE);
                mBottomProgress.setVisibility(GONE);
                mTopContainer.setVisibility(GONE);
                handleWatermarkVisible(GONE);
                break;
            case IjkVideoView.STATE_BUFFERING:
                SDKLog.info(TAG, "STATE_BUFFERING");
                mStartPlayButton.setVisibility(GONE);
                mLoadingProgress.setVisibility(VISIBLE);
                mThumb.setVisibility(GONE);
                handleWatermarkVisible(GONE);
                break;
            case IjkVideoView.STATE_BUFFERED:
                mLoadingProgress.setVisibility(GONE);
                mStartPlayButton.setVisibility(GONE);
                mThumb.setVisibility(GONE);
                handleWatermarkVisible(GONE);
                SDKLog.info(TAG, "STATE_BUFFERED");
                break;
            case IjkVideoView.STATE_PLAYBACK_COMPLETED:
                SDKLog.info(TAG, "STATE_PLAYBACK_COMPLETED");
                hide();
                removeCallbacks(mShowProgress);
                mStartPlayButton.setVisibility(GONE);
                mThumb.setVisibility(GONE);
                mCompleteContainer.setVisibility(VISIBLE);
                mBackButton.setVisibility(VISIBLE);
                mBottomProgress.setProgress(0);
                mBottomProgress.setSecondaryProgress(0);
                mIsLocked = false;
                mMediaPlayer.setLock(false);
                handleWatermarkVisible(GONE);

                if (dlnaListener != null) {
                    dlnaListener.onDLNADismissPop();
                }
                break;

            case IjkVideoView.STATE_DLNA_CONNECTED:
                mDLNAConnected = true;
                if (mFullScreen) {
                    mRlDLNAConnected_land.setVisibility(VISIBLE);
                    mRlDLNAConnected_port.setVisibility(GONE);
                } else {
                    mRlDLNAConnected_land.setVisibility(GONE);
                    mRlDLNAConnected_port.setVisibility(VISIBLE);
                }
                SDKLog.info(TAG, "STATE_DLNA_CONNECTED");
                break;
        }

        if (playState != IjkVideoView.STATE_DLNA_CONNECTED) {
            mDLNAConnected = false;
            mRlDLNAConnected_port.setVisibility(GONE);
            mRlDLNAConnected_land.setVisibility(GONE);
        }
    }

    protected void doLockUnlock() {
        if (mIsLocked) {
            mIsLocked = false;
            mShowing = false;
            mIsGestureEnabled = true;
            show();
            mLockButton.setSelected(false);
            Toast.makeText(getContext(), R.string.unlocked, Toast.LENGTH_SHORT).show();
        } else {
            hide();
            mIsLocked = true;
            mIsGestureEnabled = false;
            mLockButton.setSelected(true);
            Toast.makeText(getContext(), R.string.locked, Toast.LENGTH_SHORT).show();
        }
        mMediaPlayer.setLock(mIsLocked);
    }

    /**
     * 设置是否为直播视频
     */
    public void setLive() {
        mIsLive = true;
        mBottomProgress.setVisibility(GONE);
        mVideoProgress.setVisibility(INVISIBLE);
        mTotalTime.setVisibility(INVISIBLE);
        mCurrTime.setVisibility(INVISIBLE);
        mRefreshButton.setVisibility(VISIBLE);
    }

    /**
     * 设置是否为首次播放
     */
    public void setFirstPlay(boolean firstPlay) {
        if (firstPlay) {
            mStartPlayButton.setVisibility(VISIBLE);
        } else {
            mStartPlayButton.setVisibility(GONE);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        mIsDragging = true;
        removeCallbacks(mShowProgress);
        removeCallbacks(mFadeOut);
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        long duration = mMediaPlayer.getDuration();
        long newPosition = (duration * seekBar.getProgress()) / mVideoProgress.getMax();
        mMediaPlayer.seekTo((int) newPosition);
        mIsDragging = false;
        post(mShowProgress);
        show();
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (!fromUser) {
            return;
        }

        long duration = mMediaPlayer.getDuration();
        long newPosition = (duration * progress) / mVideoProgress.getMax();
        if (mCurrTime != null)
            mCurrTime.setText(stringForTime((int) newPosition));
    }

    @Override
    public void hide() {
        if (mShowing) {
            if (mMediaPlayer.isFullScreen()) {
                mLockButton.setVisibility(GONE);
                if (!mIsLocked) {
                    hideAllViews();
                }
            } else {
                mTopContainer.setVisibility(GONE);
                mTopContainer.startAnimation(mHideAnim);
                mBottomContainer.setVisibility(GONE);
                mBottomContainer.startAnimation(mHideAnim);
            }
            if (!mIsLive && !mIsLocked) {
                mBottomProgress.setVisibility(VISIBLE);
                mBottomProgress.startAnimation(mShowAnim);
            }
            mShowing = false;
        }
    }

    protected void hideAllViews() {
        mBackButton.setVisibility(GONE);
        mBackButton.startAnimation(mHideAnim);
        mTopContainer.setVisibility(GONE);
        mTopContainer.startAnimation(mHideAnim);
        mBottomContainer.setVisibility(GONE);
        mBottomContainer.startAnimation(mHideAnim);
    }

    private void show(int timeout) {
        if (mSysTime != null)
            mSysTime.setText(getCurrentSystemTime());
        if (!mShowing) {
            if (mMediaPlayer.isFullScreen()) {
                mLockButton.setVisibility(VISIBLE);
                if (!mIsLocked) {
                    showAllViews();
                }
            } else {
                mTopContainer.setVisibility(VISIBLE);
                mTopContainer.startAnimation(mShowAnim);
                mBottomContainer.setVisibility(VISIBLE);
                mBottomContainer.startAnimation(mShowAnim);
            }
            if (!mIsLocked && !mIsLive) {
                mBottomProgress.setVisibility(GONE);
                mBottomProgress.startAnimation(mHideAnim);
            }
            mShowing = true;
        }
        removeCallbacks(mFadeOut);
        if (timeout != 0) {
            postDelayed(mFadeOut, timeout);
        }
    }

    protected void showAllViews() {
        mBackButton.setVisibility(VISIBLE);
        mBackButton.startAnimation(mShowAnim);
        mBottomContainer.setVisibility(VISIBLE);
        mBottomContainer.startAnimation(mShowAnim);
        mTopContainer.setVisibility(VISIBLE);
        mTopContainer.startAnimation(mShowAnim);
    }

    @Override
    public void show() {
        show(mDefaultTimeout);
    }

    @Override
    public void confirmSingleTap() {
        if (mShowing) {
            hide();
        } else {
            show();
        }
    }

    @Override
    protected int setProgress() {
        if (mMediaPlayer == null || mIsDragging) {
            return 0;
        }

        if (mTitle != null && TextUtils.isEmpty(mTitle.getText())) {
            mTitle.setText(mMediaPlayer.getTitle());
        }

        if (mIsLive) return 0;

        int position = (int) mMediaPlayer.getCurrentPosition();
        int duration = (int) mMediaPlayer.getDuration();

        int playableVideoDuration = (int) (mMediaPlayer.getPlayableVideoDuration() * 1000);
        if (playableVideoDuration > 0 && playableVideoDuration < duration) {
            duration = playableVideoDuration;
        }
        if (playableVideoDuration > 0 && position >= duration) {
            mMediaPlayer.stop();
            return 0;
        }


        if (mVideoProgress != null) {
            if (duration > 0) {
                mVideoProgress.setEnabled(true);
                int pos = (int) (position * 1.0 / duration * mVideoProgress.getMax());
                mVideoProgress.setProgress(pos);
                mBottomProgress.setProgress(pos);
            } else {
                mVideoProgress.setEnabled(false);
            }
            int percent = mMediaPlayer.getBufferedPercentage();
            if (percent >= 95) { //解决缓冲进度不能100%问题
                mVideoProgress.setSecondaryProgress(mVideoProgress.getMax());
                mBottomProgress.setSecondaryProgress(mBottomProgress.getMax());
            } else {
                mVideoProgress.setSecondaryProgress(percent * 10);
                mBottomProgress.setSecondaryProgress(percent * 10);
            }
        }

        if (mTotalTime != null) {
            mTotalTime.setText(stringForTime(duration));
        }

        if (mCurrTime != null) {
            mCurrTime.setText(stringForTime(position));
        }

        // callback onProgress
        if (mMediaPlayer.getOnProgressChangeListener() != null) {
            mMediaPlayer.getOnProgressChangeListener().onProgressChange(position);
        }
        return position;
    }


    @Override
    protected void slideToChangePosition(float deltaX) {
        if (mIsLive) {
            mNeedSeek = false;
        } else {
            super.slideToChangePosition(deltaX);
        }
    }

    @Override
    public boolean onBackPressed() {
        if (mIsLocked) {
            show();
            Toast.makeText(getContext(), R.string.lock_tip, Toast.LENGTH_SHORT).show();
            return true;
        }

        Activity activity = PlayerUtils.scanForActivity(getContext());
        if (activity == null) return super.onBackPressed();

        if (mMediaPlayer.isFullScreen()) {
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            mMediaPlayer.stopFullScreen();
            return true;
        }
        return super.onBackPressed();
    }

    @Override
    protected void doPauseResume() {
        if (isPauseAdAvailable) {
//            resizePauseAd(mMediaPlayer.isFullScreen());
            if (mMediaPlayer.isPlaying()) {
                // 暂停，显示广告
                mRlPauseAd.setVisibility(VISIBLE);
                resizePauseAd(mMediaPlayer.isFullScreen());
            } else {
                mRlPauseAd.setVisibility(GONE);
            }
        }
        super.doPauseResume();
    }

    // 重新计算宽高
    private void resizePauseAd(boolean isFullScreen) {
        if (isFullScreen) {

            int height = getResources().getDisplayMetrics().heightPixels;
            int width = getResources().getDisplayMetrics().widthPixels;
            if (width >= height) {
                mRlPauseAd.getLayoutParams().width = width * 37 / 100;
                mRlPauseAd.getLayoutParams().height = height * 41 / 100;
            } else {
                mRlPauseAd.getLayoutParams().width = height * 37 / 100;
                mRlPauseAd.getLayoutParams().height = width * 41 / 100;
            }

            mTvAdDesc.setTextSize(SP, 14);
            mTvCloseAd.setTextSize(SP, 18);
            mIvcloseAd.getLayoutParams().width = Utils.dp2px(mAttachActivity, 18);
            mIvcloseAd.getLayoutParams().height = Utils.dp2px(mAttachActivity, 18);
        } else {
            ViewGroup.LayoutParams layoutParams = ((IjkVideoView) mMediaPlayer).getLayoutParams();
            mRlPauseAd.getLayoutParams().height = layoutParams.height * 37 / 70;
            mRlPauseAd.getLayoutParams().width = layoutParams.width * 41 / 70;
            mTvAdDesc.setTextSize(SP, 10);
            mTvCloseAd.setTextSize(SP, 14);
            mIvcloseAd.getLayoutParams().width = Utils.dp2px(mAttachActivity, 14);
            mIvcloseAd.getLayoutParams().height = Utils.dp2px(mAttachActivity, 14);
        }
    }

    @Override
    public void hidePausedAd() {
        mRlPauseAd.setVisibility(GONE);
    }

    private void handleWatermarkVisible(int visible) {
        if (mMediaPlayer.getWatermark() != null) {
            mRlWatermark.setVisibility(visible);
        } else {
            mRlWatermark.setVisibility(GONE);
        }
    }
}
